<?php
namespace App\Http\Logic;

use App\Models\User;
use App\Services\WechatService;
use Illuminate\Support\Facades\Storage;

class LoginLogic extends CommonLogic
{
    public static function login(string $code, string $nickname, string $avatar) : User
    {
        $service = new WechatService();

        $user_info = $service->getUserInfo($code);

        $openid = $user_info['openid'];

        $unionid = $user_info['unionid'] ?? null;

        $user = User::where('wx_open_id', $openid) -> first();

        if(!$user) {
            $avatar = saveWeixinAvatar($avatar);
            // 获取完整URL
            $avatar = Storage::disk('public')->url($avatar);
            $user = self::register($openid, $nickname, $avatar);
        }

        $user -> wx_union_id = $unionid;

        $user -> save();

        return $user;
    }

    /**
     * 手机号密码登录
     */
    public static function mpLogin($post)
    {
        $user = User::where(['phone' => $post['phone']])-> first();
        if (!$user){
            $user = self::phoneRegister($post['phone']);
        }
        $user -> save();
        return $user;
    }

    //使用手机号创建用户
    public static function phoneRegister($phone)
    {
        $data = [
            'name' => $phone,
            'wx_open_id' => '',
            'nickname' =>$phone,
            'password' => md5('123456'),
            'avatar' =>'',
            'phone' => $phone,
        ];
        $res = User::create($data);

        if(!$res) {
            self::$error = "用户创建失败";
            return false;
        }
        return User::find($res->id);
    }

    public static function register(string $openid, string $nickname, string $avatar) : User|bool
    {
        $data = [
            'name'       => $nickname,
            'wx_open_id' => $openid,
            'nickname'   => $nickname,
            'password'   => md5('123456'),
            'avatar'     => $avatar
        ];

        $res = User::create($data);

        if(!$res) {
            self::$error = "用户创建失败";
            return false;
        }

        return User::find($res->id);
    }
}
